package com.yanyu.space.common.auth;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouteFunction;
import cn.dev33.satoken.strategy.SaStrategy;
import com.yanyu.space.common.auth.support.SaTokenBeanFactoryPostProcessor;
import com.yanyu.space.common.auth.support.SaTokensPropoerties;
import com.yanyu.space.common.core.bootlog.BootstrapLogContext;
import com.yanyu.space.common.core.constants.SpaceConstants;
import com.yanyu.space.common.core.yaml.YamlPropertySourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;

/**
 * @author yanyu
 */
@Configuration
@Import(SaTokenBeanFactoryPostProcessor.class)
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:" + SpaceConstants.Properties.AUTH_PROP)
public class SaTokenAutoConfig implements WebMvcConfigurer {

    @Autowired(required = false)
    private SaRouteFunction saRouteFunction;
    @Autowired
    private SaTokensPropoerties saTokensPropoerties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器
        if (saTokensPropoerties.getAnnInterceptEnabled()) {
            registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
        }

        // 路由拦截鉴权
        if (saTokensPropoerties.getRouteInterceptEnabled()) {
            registry.addInterceptor(saRouteFunction == null ? new SaRouteInterceptor() : new SaRouteInterceptor(saRouteFunction)).addPathPatterns("/**");
        }

        BootstrapLogContext.put("sa-token", String.format("开启sa-token功能"));
    }

    @PostConstruct
    public void rewriteSaStrategy() {
        // 重写Sa-Token的注解处理器，增加注解合并功能
        SaStrategy.me.getAnnotation = (element, annotationClass) -> AnnotatedElementUtils.getMergedAnnotation(element, annotationClass);
    }
}
